import { Pipe, PipeTransform } from '@angular/core';
import { DatePipe } from '@angular/common';

@Pipe({
  name: 'TimeFormat',
})
export class TimeFormatPipe implements PipeTransform {
  transform(value?: string, type?: any): any {
    const datepipe = new DatePipe('en-US');
    const now = new Date(value);
    switch (type) {
      case 1:
        return datepipe.transform(now, 'yyyy/MM');
      case 2:
        return datepipe.transform(now, 'yyyy');
      default:
        return value;
    }
  }
}

@Pipe({
  name: 'DateFormat',
})
export class DateFormatPipe implements PipeTransform {
  /**
   * @param value 2019-01-09 16:37:05.458
   * @return any
   */
  transform(value?: string): any {
    let newDate = null;
    if (value) {
      const datepipe = new DatePipe('en-US');
      const now = datepipe.transform(new Date(), 'yyyy-MM-dd');

      const year = value.substring(0, 4);
      const month = value.substring(5, 7);
      const day = value.substring(8, 10);
      const time = value.substring(11, 16);

      const num1 = parseFloat(now.substring(0, 4) + now.substring(5, 7) + now.substring(8, 10));
      const num2 = parseFloat(year + month + day);

      if (num1 - num2 === 0) {  // 今天
        newDate = '今天 ' + time;
      } else if (num1 - num2 === 1) {  // 昨天
        newDate = '昨天 ' + time;
      } else {
        newDate = datepipe.transform(value, 'yyyy-MM-dd HH:mm');
      }
    }
    return newDate;
  }
}
